package com.qf.web;

import org.omg.SendingContext.RunTimeOperations;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
* 基类
*
* 作用:调用它的子类的方法
* */
public class BaseServlet extends HttpServlet {


    //覆盖HttpServlet的业务入口service


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //获取子类的字节码文件对象
            Class clazz = this.getClass();
            System.out.println(clazz);
            //约定的地址栏的格式
            //http://localhost:8080/maven_study_02_war/模块名称?methodName=子类的方法名
            //接收地址栏的参数:获取子类的方法名
            String methodName = request.getParameter("methodName");
            System.out.println(methodName);
            if(methodName==null){
                methodName = "index" ; //执行首页的方法
            }

            //不为空
            //创建当前类实例
            Object obj = clazz.newInstance();
            //获取子类的Method类对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

            //调用方法
            method.invoke(obj,request,response) ;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
           // e.printStackTrace(); //打印控制台日志信息
            //统一处理 运行时期异常
            throw new RuntimeException("程序反射异常...") ;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
    public  void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.out.println("baseServlet的index执行了...");
    }

}
